<template>
  <grid>
    <div class="search-header">
      <div class="left">
        <search-prompt ref="searchPrompt"
                       :total="total"
                       :cate="query.cate"
                       :keywords="query.q"></search-prompt>
      </div>
      <div class="right">
        <el-radio-group v-model="order"
                        @change="changeOrder"
                        size="mini">
          <el-radio-button label="相关度"></el-radio-button>
          <el-radio-button label="创建时间"></el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <item-list :list="list"
               class="search-content__body"
               scenes="search"
               target="_blank"></item-list>

    <el-pagination layout="total, prev, pager, next"
                   background
                   @current-change="fetch"
                   :current-page.sync="query.page"
                   :page-size="query.limit"
                   hide-on-single-page
                   style="display: flex;justify-content: center;"
                   :total="total">
    </el-pagination>
  </grid>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import itemList from "@/components/item-list";
import searchPrompt from './components/search-prompt'

export default {
  name: 'search',
  title: '搜索 | 搜寻你想要的结果把~',
  data () {
    return {
      order: '相关度',
      query: {
        page: 1,
        limit: 12,
        q: undefined,
        order: undefined,
        cate: undefined
      }
    }
  },
  components: {
    itemList, searchPrompt
  },
  computed: {
    ...mapGetters('search', ['list', 'total']),
  },
  async asyncData ({ store, route }) {
    const { query } = route;
    return store.dispatch('search/fetchList', { ...query, page: 1, limit: 12 })
  },
  mounted () {
    this.refreshQuery()
  },
  methods: {
    ...mapActions('search', ['fetchList']),
    fetch (page) {
      if (this.page) {
        this.query.page = page
      }
      this.fetchList({ ...this.query })
    },
    changeOrder (order) {
      if (order === '相关度') {
        this.query.order = undefined
      } else {
        this.query.order = 'time_publish_desc'
      }
      this.fetch(1)
    },
    refreshQuery () {
      const { query } = this.$route;
      this.query.q = query.q || undefined
      this.query.cate = query.cate || undefined
    }
  },
  watch: {
    $route: function (newVal, oldVal) {
      this.$nextTick(() => {
        this.refreshQuery()
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.search-header {
  padding: 10px 0 8px 0;
  line-height: 28px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f6f6f6;
}
</style>